/**
 * Copyright(c)2012 Beijing PeaceMap Co.,Ltd.
 * All right reserved. 
 */
package com.pmc.dwa.security.intercept;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.pmc.dwa.common.exception.PmcAccessDeniedException;
import com.pmc.dwa.common.exception.PmcRuntimeException;
import com.pmc.dwa.common.utils.ConfigParameter;
import com.pmc.dwa.security.model.TRole;
import com.pmc.dwa.security.model.TUserDetails;
import com.pmc.dwa.security.service.IUserService;

/**
 * @description 项目实现的用户查询服务,将用户信息查询出来(用于实现用户的认证)
 * @author aokunsang
 * @date 2013-1-6
 */
public class PmcUserDetailService implements UserDetailsService {

	private IUserService userService;
	
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		if(StringUtils.isEmpty(username)){
			throw new PmcRuntimeException("用户名不能为空!");
		}
		TUserDetails userDetails = userService.findUserDetailsByUserName(username);
		if(userDetails==null || userDetails.getUserid() == null){
			throw new UsernameNotFoundException("该用户名[USERNAME="+username+"]不存在！");
		}
		if("0".equals(userDetails.getUstatus())){
			throw new PmcRuntimeException("该用户[USERNAME="+username+"]已经被禁用,请与管理员联系。");
		}
		Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
		List<TRole> roles = userService.findUserRolesByUsername(username);
		if(roles==null || roles.isEmpty()){
			throw new PmcRuntimeException("该用户[USERNAME="+username+"]还没有分配任何权限,请与管理员联系。");
		}
	//------------获取角色和groupid之间关系Map--------
		Collection<String> allRoles = null;
		boolean result = false;   //决策登录用户是否有权限
		try {
			String groupid = ConfigParameter.getParamVal("sysconf.properties", "groupid");
			Map<String,Collection<String>> listMap = PmcSecurityMetadataSource.getAllRoleGroupid();
			if(listMap!=null){
				allRoles = listMap.get(groupid);
			}
		} catch (Exception e) { 
			result = true;    //如果没有找到sysconf.properties文件，视为可登录
		}
		for(TRole role : roles){
			GrantedAuthority ga = new SimpleGrantedAuthority(role.getRolename());
			authorities.add(ga);
			if(allRoles!=null && allRoles.contains(role.getRolename())){  //根据角色判断用户是否可以登录
				result = true;
			}
		}
		if(!result) throw new PmcAccessDeniedException("登录用户没有该系统的登录权限。");
		userDetails.setAuthorities(authorities);
		return userDetails;
	}

	/**
	 * @param userService the userService to set
	 */
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

}
